/**
 * Copyright (c) 2002-2012 旭鸣信息
 * All rights reserved. 
 * File：FrontGoodsCollectionDaoImpl.java
 * History: Dec 27, 2012: Initially created, liuzhi.
 */
package com.xteam.ecsystem.dao.Impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.dao.IFrontGoodsCollectionDao;
import com.xteam.ecsystem.entities.BaseGoodsCollection;
import com.xteam.ecsystem.entities.BaseGoodsInfo;
import com.xteam.ecsystem.utils.PageCenterStation;

/**
 * 前端商品收藏数据访问实现类
 * @author liuzhi
 *
 */
@Repository
public class FrontGoodsCollectionDaoImpl extends DDLPrefix implements IFrontGoodsCollectionDao {
	
	@SuppressWarnings("unchecked")
	@Autowired
	private BaseDaoImpl baseDao;

	@SuppressWarnings("unchecked")
	public PageCenterStation<?> getGoodsCollectionList(String bgcMember, int pageIndex, int pageSize) {
		try {
			List list = new ArrayList();
			
			// 直接使用连接查询得到的是数组而不是json数据，因此此处的构造函数就是用于构建json类型的数据。
			String hql = SQL_SELECT 
					+ " new " + BaseGoodsCollection.REF 
					+ " (bgc.bgcId, bgc.bgcMember, bgc.bgcGoods, bgc.bgcTime, bgi.bgiName, bgi.bgiPrice)" 
					+ SQL_FROM  
					+ BaseGoodsCollection.REF + " as bgc, " 
					+ BaseGoodsInfo.REF + " as bgi "  
					+ SQL_WHERE 
					+ " bgc.bgcGoods = bgi.bgiId "
					+ SQL_AND 
					+ "bgc.bgcMember = ?"
					+ SQL_ORDERBY 
					+ "bgc.bgcTime desc";
			
			String countHQL = SQL_SELECT 
					+ " count(*) " 
					+ SQL_FROM 
					+ BaseGoodsCollection.REF + " as bgc, " 
					+ BaseGoodsInfo.REF + " as bgi " 
					+ SQL_WHERE 
					+ " bgc.bgcGoods = bgi.bgiId "
					+ SQL_AND 
					+ "bgc.bgcMember = ?";
			
			list.add(bgcMember);
			
			PageCenterStation<?> p = (PageCenterStation<?>) this.baseDao.queryList(countHQL, hql, list
					.toArray(), (pageIndex - 1) * pageSize, pageSize);
			
			return p;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	public void delFromFav(String bmbId, String goodsId){
		try {
			String hql = SQL_DELETE + SQL_FROM + BaseGoodsCollection.REF + SQL_WHERE + "bgcMember=?"
					+ SQL_AND + "bgcGoods=?";
			
			this.baseDao.executeUpdate(hql, new Object[]{bmbId, goodsId});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public BaseGoodsCollection getUserFav(String bmbId, String goodsId){
		try {
			String hql = SQL_FROM + BaseGoodsCollection.REF + SQL_WHERE + "bgcMember=?"
					+ SQL_AND + "bgcGoods=?";
			
			Object obj = this.baseDao.findObject(hql, new Object[]{bmbId, goodsId});
			
			if(obj != null) return (BaseGoodsCollection)obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	public void saveUserFav(BaseGoodsCollection obj){
		try {
			this.baseDao.save(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
